/**
 * Created by dong on 16/1/21.
 */

'use strict';
let gulpCommon = module.exports = {};
var gulp = require('gulp');

// 重启 小强
gulpCommon.restartConsumer = (hostIp,userName,passWord,projectRoot)=>{
    let gulpSSH = gulpCommon.getSshInstance(hostIp,userName,passWord);
    //连续执行命令这样就可以的了.
    //注NPM3 会执行失败, 目前只有测试环境1是NPM3
    let _Dir ='cd '+projectRoot +';';
    //rm -rdf ./node_modules/x-site-ui && node ./bin/ui-c-bin.js &&  npm run transferJsx && pm2 restart xx && pm2 logs
    //npm install --registry=http://registry.npm.qianmi.com && cd public && npm install --registry=http://registry.npm.qianmi.com  && pm2 restart xx  && pm2 logs
    let execCmands =[
        _Dir,
        //'rm -rdf ./node_modules/x-site-ui;',//
        'npm install --registry=http://registry.npm.qianmi.com',
        //'node ./bin/ui-c-bin.js',//
        'cd public',
        'npm install --registry=http://registry.npm.qianmi.com',
        //'npm run transferJsx',//
        'pm2 restart xx',
        //'npm run pm2xx',
    ];
    //.map(cmdItem=>_Dir+cmdItem);

    //return gulpSSH.exec(execCmands,{filePath:'gulp.log'}).pipe(gulp.dest('logs'));
    return gulpSSH.shell(execCmands,{filePath:'consumer-restart-'+hostIp+'.log'}).pipe(gulp.dest('logs'));
}


// 重启web
//注, 目前build代码 会在本地进行编译. 所以要注意...
gulpCommon.restartWeb = ({hostIp,userName,passWord,projectRoot,preCmds=[],afterCmds=[]})=>{

    let gulpSSH = gulpCommon.getSshInstance(hostIp,userName,passWord);
    let _Dir = 'cd '+projectRoot +';';
    let execCmands = [
        _Dir,
        'npm install --registry=http://registry.npm.qianmi.com',// web 服务端打包.
        'pm2 --node-args="--harmony-async-await" restart xsite -k 50000',
        //'exit'
        //'pm2 start ./bin/www --name xsite',
    ];
    return gulpSSH.shell(preCmds.concat(execCmands).concat(afterCmds),{filePath:'web-restart-'+hostIp+'.log'})
       .pipe(gulp.dest('logs'));
}



gulpCommon.getSshInstance = (host, userName, passWord)=> {

    return new require('gulp-ssh')({
        ignoreErrors: true,
        sshConfig: {
            host: host,
            port: 22,
            username: userName,
            password: passWord
        }
    });
}

gulpCommon.getFtpInstance = (host, userName, passWord, projectRoot) => {

    return require('gulp-sftp')({
        host: host,
        user: userName,
        pass: passWord,
        port: 22,
        remotePath: projectRoot
    });
}